import { fetchPermission } from "@/api";
import router, { DynamicRoutes } from "@/router";
import dynamicRouter from "@/router/dynamic-router";
import { recursionRouter, setDefaultRoute } from "@/utils/recursion-router";

export default {
  namespaced: true,
  state: {
    permissionList: null,
    sidebarMenu: [],
    currentMenu: "",
    allMenus: []
  },
  getters: {},
  mutations: {
    SET_PERMISSION(state, routes) {
      state.permissionList = routes;
    },
    CLEAR_PERMISSION(state) {
      state.permissionList = null;
    },
    SET_MENU(state, menus) {
      state.allMenus = menus;
    },
    CLEAR_MENU(state) {
      state.allMenus = [];
    }
  },
  actions: {
    async FETCH_PERMISSION({ commit, state }) {
      let res = await fetchPermission();
      let permissionList = res.data;
      let routes = recursionRouter(permissionList, dynamicRouter);
      let MainContainer = DynamicRoutes.find(v => v.path === "");
      let children = MainContainer.children;
      children.push(...routes);
      commit("SET_MENU", children);
      setDefaultRoute([MainContainer]);
      let initialRoutes = router.options.routes;
      commit("SET_PERMISSION", [...initialRoutes, ...DynamicRoutes]);
      DynamicRoutes.forEach(item => {
        router.addRoute(item);
      });
    }
  }
};
